import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:event_bus/event_bus.dart';

import '../event/event_param.dart';
import '../tools/tools_dictionary.dart';

class PanelQueryWord extends StatefulWidget {
  // const
  PanelQueryWord({super.key});

  @override
  State<PanelQueryWord> createState() => _PanelQueryWordState();
}

class _PanelQueryWordState extends State<PanelQueryWord>
    with AutomaticKeepAliveClientMixin {
  List<String> queryWordStack = [];
  int curIndex = -1;

  TextEditingController _textEditingController = new TextEditingController();

  Map<String, dynamic> words = {};

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    queryWordStack = [];

    loadJsonFromAssets("asserts/dict.json").then((value) {
      words = value;
      print(words);
    });

    // DictionaryTools.eventBus.on().listen((event) {
    //   print(event);
    // });
    ToolsDictionary.eventBus.on<EventParam>().listen((EventParam data) {
      print(data.getWord);
      query_word(data.getWord);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(5.0),
      child: Column(
        children: [
          buildSearchBar(),
          queryWordStack.length > 0 ? buidlWordPanel() : buildQueryHistory()
        ],
      ),
    );
  }

  // 搜索栏
  buildSearchBar() {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Container(
        decoration: BoxDecoration(
            border:
                Border(bottom: BorderSide(width: 1, color: Color(0xffe5e5e5)))),
        child: Row(
          children: [
            Expanded(
              child: TextField(
                  onSubmitted: (value) {
                    op("query_word");
                  },
                  textAlign: TextAlign.center,
                  controller: _textEditingController,
                  autofocus: true,
                  decoration: InputDecoration(
                      hintText: "请输入单词", border: InputBorder.none)),
            ),
            Offstage(
              offstage: _textEditingController.text.isEmpty ? true : false,
              child: GestureDetector(
                onTap: () {
                  setState(() {
                    _textEditingController.clear(); //清除textfield的值
                  });
                },
                child: Container(
                  width: 45,
                  height: 45,
                  child: Icon(
                    Icons.cancel,
                    color: Colors.grey,
                    size: 17,
                  ),
                ),
              ),
            ),
            TextButton(
                onPressed: () {
                  op("query_word");
                },
                child: Text("查询"))
          ],
        ),
      ),
    );
  }

  // 查询历史
  buildQueryHistory() {
    return Container(
      child: Text("查询历史"),
    );
  }

  // 单词面板
  buidlWordPanel() {
    return Container(
        child: Column(children: [buildWordBar(), buildWordResult()]));
  }

  buildWordBar() {
    return Row(
      children: [
        IconButton(
            onPressed: () {
              op("prev_word");
            },
            icon: Icon(Icons.keyboard_arrow_left)),
        curIndex + 1 != queryWordStack.length
            ? IconButton(
                onPressed: () {
                  op("next_word");
                },
                icon: Icon(Icons.keyboard_arrow_right))
            : SizedBox(
                width: 1,
              ),
        Text(queryWordStack[curIndex]),
        IconButton(onPressed: () {}, icon: Icon(Icons.add_circle_outline)),
        TextButton(onPressed: () {}, child: Text("更多"))
      ],
    );
  }

  buildWordResult() {
    return Column(
      children: [
        // Container(
        //   child: Text("词库列表"),
        // ),
        // Container(
        //   child: Text("发音"),
        // ),
        // Container(
        //   child: Text("单词释义"),
        // ),
        Container(
          child: words[queryWordStack[curIndex]] != null
              ? Text(words[queryWordStack[curIndex]])
              : Text(""),
        )
        // Container(
        //   child: Text("例句"),
        // )
      ],
    );
  }

  void op(String op) {
    switch (op) {
      case "prev_word":
        curIndex--;
        print("curIndex=${curIndex}");
        if (curIndex == -1) {
          while (queryWordStack.length > 0) {
            queryWordStack.removeLast();
          }
        }
        // 前一词
        setState(() {});
        break;
      case "next_word":
        print("curIndex=${curIndex}");
        // 后一词
        setState(() {
          if (queryWordStack.length - 1 > curIndex) {
            curIndex++;
          }
        });
        break;
      case "query_word":
        // 查询单词
        String word = _textEditingController.text;
        print("查询" + word);

        query_word(word);

        break;
      case "word_more":
        // 单词更多信息
        break;
      case "add_new":
        // 添加为生词
        break;
    }
  }

  query_word(String word) {
    if (word.length > 0) {
      while (queryWordStack.length > curIndex + 1) {
        queryWordStack.removeLast();
      }
      queryWordStack.add(word.toLowerCase());
      print("长度:${queryWordStack.length}");
      curIndex++;
      setState(() {});
    }
  }

  @override
  bool get wantKeepAlive => true;
}
